<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input size="small" v-model.trim="listQuery.title" placeholder="权限名称" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 20px">
        查询
      </el-button>
      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

    </div>

    <el-table
      v-loading="listLoading"
      :data="list.slice((currentPage-1)*PageSize,currentPage*PageSize)"
      row-key="name"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="权限名称" >
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="权限规则" >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="级别" >
        <template slot-scope="scope">
          {{ scope.row.level }}级
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page.sync="currentPage"
                   :page-sizes="pageSizes"
                   :page-size="PageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>


    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="dialogFormClose">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="50px" style="width: 400px; margin-left:50px;">
        <el-form-item label="顶级权限或上一级权限" prop="f_id" label-width="170px">
          <el-select  v-model="temp.f_id" placeholder="顶级权限上一级权限" clearable style="width: 300px;" class="filter-item">
            <el-option v-for="item in citys" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限名称" prop="title" label-width="80px">
          <el-input v-model="temp.title" placeholder="权限名称" />
        </el-form-item>
        <el-form-item label="权限规则" prop="name" label-width="80px">
          <el-input v-model="temp.name" placeholder="权限名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {
  getAuthRule,
  updateAuthRule,
  createAuthRule,
  deleteAuthRule
} from '@/api/auth_rule'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
export default {
  filters: {
    adminStatusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'danger'
      }
      return statusMap[status]
    },
  },
  data() {
    return {
///////////////自定义分页////////////////////////
      // 总数据
      // tableData:[],
      // 默认显示第几页
      currentPage:1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      // totalCount:1,
      // 个数选择器（可修改）
      pageSizes:[10,20,30,40],
      // 默认每页显示的条数（可修改）
      PageSize:10,
/////////////////////////////
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      citys:'',
      token:'',
      downloadLoading:false,
      table_name:'用户数据导出',
      importanceOptions:[
        {'label': '正常','value':0},
        {'label': '禁用','value':1},
      ],
      total: 1,
      listQuery: {
        // page: 1,
        // limit: 10,
        title: undefined,
      },
      list: [],
      listLoading: true,
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '权限规则不能为空', trigger: 'blur' }],
        f_id: [{ required: true, message: '顶级或上一级权限不能为空', trigger: 'blur' }],
      },
      //新增和编辑数据
      temp: {
        title:undefined,
        f_id:undefined,
        name: undefined
      },
      dialogStatus:'',
      dialogFormVisible: false,
    }
  },
  created() {
    //获取数据
    this.fetchData()
    // this.getTree2()
  },
  computed:{
    tokenFig(){
      return {token:getToken()}
    }
  },
  methods: {
//////////自定义分页////////////////
    // 分页
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize=val
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.currentPage=1
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.currentPage=val
    },
////////////////////////////////
    //查询
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    //关闭弹窗的新增和修改
    dialogFormClose(){
      this.resetTemp()
      this.dialogFormVisible = false
    },
    //按钮唤起新增
    handleCreate() {
      // this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //新增操作方法
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAuthRule(this.temp).then((res) => {
            this.resetTemp()
            if(res.status==200){
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.dialogFormVisible = false
              this.fetchData()
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        title:undefined,
        f_id:undefined,
        name: undefined
      }
    },
    //按钮唤起编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑操作方法
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateAuthRule(tempData).then((res) => {
            if(res.status==200){
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.fetchData()
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    //查询列表数据
    fetchData() {
      this.listLoading = true
      getAuthRule(this.listQuery).then(response => {
        // this.list = response.data.items
        this.list = response.data
        this.citys = response.data2
        this.total = response.total
        this.listLoading = false
      })
    },
    //删除列表数据
    handleDelete(row, index) {
      deleteAuthRule({id:row.id}).then(response => {
        // this.list = response.data.items
        if(response.status==200){
          this.$notify({
            title: 'Success',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          //this.list.splice(index, 1)
          this.fetchData()
        }else{
          this.$notify({
            title: 'Error',
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    cancel(){
      this.dialogFormVisible = false
      this.resetTemp()
    }

  },
  components:{
    Pagination
  }
}
</script>
<style>
.filter-container{
  padding-bottom: 20px;
}
</style>
